package com.aha.firstchapter.second;

/**
 * 冒泡排序
 * Created by wangxin on 2015/10/27.
 */
public class BubbleSort {
    public static void main(String[] args) {
        int[] arr = {1,2,3,4,7,6,9,2,8,8};
        BubbleSort bs = new BubbleSort();
        bs.start(arr);
    }
    public void start(int[] arr){
        boolean mark;//标记这一次循环是否有交换,如果没有交换则说明已排好序跳出循环
        int sum = 0;
        int len = arr.length;
        for (int i = 0; i < len-1; i++) {
            mark = false;
            for (int j = 0; j < len-i-1; j++) {
                if(arr[j] > arr[j+1]){
                    arr[j] = arr[j] + arr[j+1];
                    arr[j+1] = arr[j] - arr[j+1];
                    arr[j] = arr[j] - arr[j+1];
                    mark = true;
                }
                sum++;
            }
            if(!mark) break;
        }
        System.out.println("循环了" + sum);
        for (int p = 0; p < arr.length; p++) {
            System.out.println(arr[p]);
        }
    }
}
